<template>
  <div class="panel-tab__content">
    <a-table :data-source="elementPropertyList" size="small" :scroll="{ y: 240 }" bordered>
      <a-table-column title="序号" width="50px">
        <template #customRender="{ index }">
          {{ index + 1 }}
        </template>
      </a-table-column>
      <a-table-column title="属性名" data-index="name" width="100px" :ellipsis="true" />
      <a-table-column title="属性值" data-index="value" width="100px" :ellipsis="true" />
      <a-table-column title="操作" width="90px">
        <template #customRender="{ record, index }">
          <a-space>
            <a @click="openAttributesForm(record, index)">编辑</a>
            <a-divider type="vertical" />
            <a class="text-red" @click="removeAttributes(record, index)">移除</a>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <div class="element-drawer__button">
      <a-button size="small" type="primary" @click="openAttributesForm(null, -1)">
        <template #icon><plus-outlined /></template>
        添加属性
      </a-button>
    </div>

    <a-modal v-model:open="propertyFormModelVisible" title="属性配置" width="600px" :destroy-on-close="true" @ok="saveAttribute">
      <a-form ref="attributeFormRef" :model="propertyForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" size="small">
        <a-form-item label="属性名" name="name" :rules="[{ required: true, message: '请输入属性名' }]">
          <a-input v-model:value="propertyForm.name" allow-clear />
        </a-form-item>
        <a-form-item label="属性值" name="value" :rules="[{ required: true, message: '请输入属性值' }]">
          <a-input v-model:value="propertyForm.value" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import { PlusOutlined } from '@ant-design/icons-vue';

  export default {
    name: 'ElementProperties',
    components: {
      PlusOutlined,
    },
    props: {
      id: String,
      type: String,
    },
    inject: {
      prefix: 'prefix',
      width: 'width',
    },
    data() {
      return {
        elementPropertyList: [],
        propertyForm: {},
        editingPropertyIndex: -1,
        propertyFormModelVisible: false,
      };
    },
    watch: {
      id: {
        immediate: true,
        handler(val) {
          val && val.length && this.resetAttributesList();
        },
      },
    },
    methods: {
      resetAttributesList() {
        this.bpmnElement = window.bpmnInstances.bpmnElement;
        this.otherExtensionList = []; // 其他扩展配置
        this.bpmnElementProperties =
          this.bpmnElement.businessObject?.extensionElements?.values?.filter((ex) => {
            if (ex.$type !== `${this.prefix}:Properties`) {
              this.otherExtensionList.push(ex);
            }
            return ex.$type === `${this.prefix}:Properties`;
          }) ?? [];

        // 保存所有的 扩展属性字段
        this.bpmnElementPropertyList = this.bpmnElementProperties.reduce((pre, current) => pre.concat(current.values), []);
        // 复制 显示
        this.elementPropertyList = JSON.parse(JSON.stringify(this.bpmnElementPropertyList ?? []));
      },
      openAttributesForm(attr, index) {
        this.editingPropertyIndex = index;
        this.propertyForm = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
        this.propertyFormModelVisible = true;
        this.$nextTick(() => {
          if (this.$refs['attributeFormRef']) this.$refs['attributeFormRef'].clearValidate();
        });
      },
      removeAttributes(attr, index) {
        this.$confirm('确认移除该属性吗？', '提示', {
          confirmButtonText: '确 认',
          cancelButtonText: '取 消',
        })
          .then(() => {
            this.elementPropertyList.splice(index, 1);
            this.bpmnElementPropertyList.splice(index, 1);
            // 新建一个属性字段的保存列表
            const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
              values: this.bpmnElementPropertyList,
            });
            this.updateElementExtensions(propertiesObject);
            this.resetAttributesList();
          })
          .catch(() => console.info('操作取消'));
      },
      saveAttribute() {
        const { name, value } = this.propertyForm;
        console.log(this.bpmnElementPropertyList);
        if (this.editingPropertyIndex !== -1) {
          window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.bpmnElementPropertyList[this.editingPropertyIndex], {
            name,
            value,
          });
        } else {
          // 新建属性字段
          const newPropertyObject = window.bpmnInstances.moddle.create(`${this.prefix}:Property`, { name, value });
          // 新建一个属性字段的保存列表
          const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
            values: this.bpmnElementPropertyList.concat([newPropertyObject]),
          });
          this.updateElementExtensions(propertiesObject);
        }
        this.propertyFormModelVisible = false;
        this.resetAttributesList();
      },
      updateElementExtensions(properties) {
        const extensions = window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {
          values: this.otherExtensionList.concat([properties]),
        });
        window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
          extensionElements: extensions,
        });
      },
    },
  };
</script>

<style>
  .panel-tab__content {
    padding: 8px;
  }

  .text-red {
    color: #ff4d4f;
  }

  .element-drawer__button {
    margin-top: 8px;
    text-align: right;
  }
</style>
